<template>
    <div>
        <rui-page :defines="defines">
            <Form ref="prototypeForm" :model="prototypeForm.productPlan" :rules="prototypeFormValidate" :label-width="250">
                <div class="basis-info">
                    <Alert>
                        <h2>基本信息</h2>
                    </Alert>
                    <br>
                    <Row>
                        <Col :xs="24" :md="24" :lg="16" :xl="12">
                            <FormItem label="批次编号" prop="planNumber">
                                <Input v-model="prototypeForm.productPlan.planNumber" v-bind:disabled="true" style="width: 200px"/>
                            </FormItem>
                        </Col>
                        <Col :xs="24" :md="24" :lg="16" :xl="12">
                            <FormItem label="批次名称" prop="planName">
                                <Input  v-model="prototypeForm.productPlan.planName" v-bind:disabled="isreadonly" style="width: 200px"/>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col :xs="24" :md="24" :lg="16" :xl="12">
                            <FormItem label="生效日期" prop="effectiveDate">
                                <DatePicker v-model="prototypeForm.productPlan.effectiveDate" style="width: 200px" type="date" format="yyyy-MM-dd" v-bind:disabled="isreadonly"/>
                            </FormItem>
                        </Col>
                        <Col :xs="24" :md="24" :lg="16" :xl="12">
                            <FormItem label="结束时间" prop="endTime">
                                <DatePicker v-model="prototypeForm.productPlan.endTime" style="width: 200px" type="date" format="yyyy-MM-dd" v-bind:disabled="isreadonly"/>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span="24">
                            <FormItem label="备注" prop="remark">
                                <Input type="textarea" v-model="prototypeForm.productPlan.remark" v-bind:disabled="isreadonly" style="width: 60%"/>
                            </FormItem>
                        </Col>
                    </Row>
                </div>

                <!-- 原子参数 -->
                <productUpdateInfomationAtom
                    ref="pricingParameters"
                    :parentParam="parentParam"
                    :formDataJson="prototypeForm.json"
                    :templateCategory="templateCategory"
                    :readOnly="op=='view'"
                    @repaymentChange="repaymentChange"
                />
                <!--还款方式参数-->
                <repayment-method-parameters
                    ref="repaymentMethodParameters"
                    :methodParametersForm="prototypeForm.methodParametersForm"
                    :repaymentMethod="repaymentMethod"
                    @methodParametersChange="methodParametersChange"
                    :parentParam="parentParam"
                />
                <!--利率-->
                <product-plan-rate
                    ref="productPlanRate"
                    :parentParam="parentParam"
                    @rateChange="rateChange"
                    :planRatejson="prototypeForm.planRatejson"
                    :rateType="rateType"/>
                <!--方案选择-->
                <productUpdateInfomationSelect
                    :productPlan="prototypeForm.productPlan"
                    :discountType="discountType"
                    :isRiskPricing="isRiskPricing"
                    :isAddLoan="isAddLoan"
                    :templateCategory="templateCategory"
                    :parentParam="parentParam"
                    ref="productSchemeSelection"
                />

            </Form>
            <Alert  v-show="parentParam.status!='view'">
                <Row style="text-align: center;">
                    <Button type="primary" icon="md-bookmark" @click="save" :loading="submitLoading">保存</Button>
                </Row>
            </Alert>

            <Alert v-show="parentParam.status=='view'">
                <h2>产品方案</h2>
            </Alert>
            <rui-table
                :defineId="'productPlanDefine'"
                :fixedLeft="['action']"
                :showIndex="false"
                :select="false"
                :columns="planColumns"
                :slots="[{key:'action',slot:'action'},{key:'productName',slot:'productName'}]"
                @loadDatas="queryData"
                ref-query="searchFormManage"
                ref="productPlanTable"
            >
                <template slot="toolBar">
                    <Button @click="add" type="primary" icon="md-add"  v-show="'view'!== op">新增</Button>
                </template>
                <template slot="action" slot-scope="{ row }">
                    <div>
                        <Button type="error" size="small" @click="remove(row)"  v-show="'view'!== op">删除</Button>
                    </div>
                </template>
                <template slot-scope="{ row, index }" slot="productName">
                    <a @click="view(row)">
                        {{row.productName}}
                    </a>
                </template>
            </rui-table>

            <div>
                <commonApproveRecord :stageId="planId" v-if="'view'==op"/>
            </div>
            <commonProductUpdate v-if="modalVisible" :modalTitle="modalTitle" :parentParam="parentParam" @backInfo="backInfo" @backResult="backResult"/>
        </rui-page>
    </div>
</template>
<script>
    import validator from '_p/afs-core-business/pages/product/common/rules.js';
    import productUpdateInfomationSelect from "./productUpdateInfomationSelect.vue";
    import productUpdateInfomationAtom from "./productUpdateInfomationAtom.vue";
    import productPlanRate from "../product-prototype/productPlanRate.vue";
    import repaymentMethodParameters from "../product-prototype/repaymentMethodParameters.vue";
    import commonProductUpdate from "@/projects/afs-core-business/pages/product/common/common-product-update.vue";
    import commonApproveRecord from "../common/common-approve-record.vue";

    import {deepClone} from '@/libs/utils/ObjectClone'
    import {getByTypes} from "_p/basic/api/admin/datadic";

    import {
        getPrototypeInfo,
        saveProductProposal,
        queryProductUpdatePlanList,
        saveProductUpdatePlan,
        delUpdatePlanById
    } from "@/projects/afs-core-business/api/afs-product/product-plan-approve/approve";

    import productPlanDefine from "../product-plan/define/product-plan-table-define";

    export default {
        name: "product-prototype",
        components: {
            productUpdateInfomationSelect,
            productUpdateInfomationAtom,
            productPlanRate,
            repaymentMethodParameters,
            commonProductUpdate,
            commonApproveRecord,
        },
        props: {
            //方案ID
            planId:{
                type:String,
            },
            //状态
            op:{
                type:String,
                required: true,
                default: 'view'
            },
            //修改信息
            parentParam:{
                type:Object,
            },
        },
        data() {
            return {
                rateType: null,
                isreadonly: false,
                repaymentMethod: null,
                discountType: null,
                isRiskPricing: null,
                isAddLoan: null,
                templateCategory: null,
                submitLoading: false,
                productCategory: [],
                prototypeFormValidate: {
                    // planNumber: [ {required: true, message: "编号不能为空",trigger: "change"}, {validator: validator.numAndLetterValidator, trigger: "change"},],
                    planName: [ {required: true, message: "产品名称不能为空",trigger: "change"}],
                    effectiveDate: [ {required: true, message: "生效日期不能为空",trigger: "change",type: 'date'}],
                    // endTime: [ {required: true, message: "结束时间不能为空",trigger: "change",type: 'date'}],
                },
                isdisabled: true,
                prototypeForm: {
                    repaymentType: "",
                    rateType: "",
                    productPlan: {
                        extrasPlanId: '',
                        extrasPlanName: '',
                        discountPlanId: '',
                        discountPlanName: '',
                        launchPlanId: '',
                        launchPlanName: '',
                        financePlanId: '',
                        financePlanName: '',
                        riskPlanId: '',
                        riskPlanName: '',
                    },
                    planRatejson: [],
                    json: {},
                    methodParametersForm: {
                        repaymentMethods: {
                            finalPaymentBenchmark: null,
                            finalPaymentCalculationLogic: null,
                            intervalSelectionFinalPayment: null,
                            fromBalancePaymentInterval: null,
                            endBalancePaymentRange: null,
                            floatingProportionStepLoan: null,
                            numberStepsPerStep: null,
                            adjustedMinimumMode: null,
                            adjustedMonthlyPayments: null,
                            monthlyPaymentPercentage: null,
                            firstNMinimumLimit: null,
                            setAnyNumberCredits: null,
                            percentageTotalRepayment: null,
                            monthlySupplyAmount: null,
                            totalAmountInstalments: null,
                            paymentType: null,
                        },
                        data: []
                    }
                },

                //列表显示字段
                planColumns: [],
                //弹窗
                modalTitle:'新增上线产品',
                modalVisible:false,
            }
        },
        created() {
            let {status,productTemplateId,templateCategory} = this.parentParam;
            this.prototypeForm.productPlan.productTemplateId = productTemplateId;//模板ID
            this.prototypeForm.productPlan.templateCategory = templateCategory;//模板编号
            if ("view" == status) {
                this.isreadonly = true;
            }
        },
        mounted() {
            this.initDatadic();
            let {status, id} = this.parentParam;
            if ("view" == this.op) {
                this.planColumns=['productNumber', 'productName', 'templateName', 'createTime'];
                this.getInfo(id);
                this.refresh();
            }
            if ("edit" == this.op) {
                this.planColumns=['action', 'productNumber', 'productName', 'templateName', 'createTime'];
                this.getInfo(id);
                this.refresh();
            }
            if ("add" == this.op){
                this.planColumns=['action', 'productNumber', 'productName', 'templateName', 'createTime'];
            }
        },
        methods: {
            initDatadic() {
                //数据字典
                let arr = ["productCategory"];
                getByTypes(arr).then(res => {
                    if (res.code === "0000") {
                        this.productCategory.push(...res.data.productCategory);
                    }
                });
            },
            getInfo(id) {
                getPrototypeInfo({id: id,readOnly:this.op=='view'?true:false}).then(res => {
                    if ("0000" === res.code) {
                        this.prototypeForm.productPlan = deepClone(res.data.productUpdate);
                        this.templateCategory = this.prototypeForm.productPlan.templateCategory;
                        if (res.data.methodParametersForm != null) {
                            this.prototypeForm.methodParametersForm = deepClone(res.data.methodParametersForm);
                        }
                        if (res.data.productUpdateRates != null) {
                            this.prototypeForm.planRatejson = deepClone(res.data.productUpdateRates);
                        }
                        if (res.data.json != null) {
                            this.prototypeForm.json = deepClone(res.data.json);
                        }
                    }
                })
            },
            backPage() {
                this.$emit('backPage', "退回");
            },
            changeTimestyle(oldtime) {
                var date = new Date(Date.parse(new Date(oldtime)) + 8 * 3600 * 1000);
                return date;
            },
            //保存
            save() {
                this.prototypeForm.json = this.$refs.pricingParameters.formData;
                const data = this.prototypeForm;
                let parms = [
                    this.$refs.pricingParameters.getForm(),
                    this.$refs.prototypeForm,
                ];
                let flag1 = this.$refs['productSchemeSelection'].validateForm();
                let flag2 = this.$refs['repaymentMethodParameters'].validateForm();
                // 使用Promise.all去校验结果
                Promise.all(parms.map(this.getFormPromise)).then(res => {
                    const validateResult = res.every(item => !!item);
                    if (validateResult && flag1 && flag2) {
                        // if (data.productPlan.effectiveDate != "") {
                        //     data.productPlan.effectiveDate = this.changeTimestyle(data.productPlan.effectiveDate);
                        // }
                        // if (data.productPlan.endTime != "") {
                        //     data.productPlan.endTime = this.changeTimestyle(data.productPlan.endTime);
                        // }
                        this.submitLoading = true;
                        saveProductProposal(data).then(res => {
                            this.submitLoading = false;
                            if (res.code === "0000") {
                                this.prototypeForm.productPlan = res.data;
                                // this.backPage();
                                this.$emit('backResult', this.prototypeForm.productPlan.id);
                                this.$Message.success("保存成功！");
                            } else {
                                this.$Message.error(res.msg);
                            }
                        }).catch(() => {
                            this.submitLoading = false;
                        });
                    }
                })
            },
            getFormPromise(form) {
                return new Promise(resolve => {
                    form.validate(res => {
                        resolve(res);
                    })
                })
            }
            ,
            repaymentChange(val) {
                if ("repaymentType" == val.type) {
                    this.repaymentMethod = val.value;
                    this.prototypeForm.repaymentMethod = val.value;
                } else if ("rateType" == val.type) {
                    this.rateType = val.value;
                    this.prototypeForm.rateType = val.value;
                } else if ("isAddLoan" == val.type) {
                    this.isAddLoan = val.value;
                    this.prototypeForm.isAddLoan = val.value;
                } else if ("isRiskPricing" == val.type) {
                    this.isRiskPricing = val.value;
                    this.prototypeForm.isRiskPricing = val.value;
                } else if ("discountType" == val.type) {
                    console.info("监控贴息数据"+JSON.stringify(val));
                    this.discountType = val.value;
                    this.prototypeForm.discountType = val.value;
                }
            },
            rateChange(val) {
                this.prototypeForm.planRatejson = val;
            },
            methodParametersChange(val) {
                this.prototypeForm.methodParametersForm = val;
            },

            //列表初始化
            refresh() {
                this.$refs['productPlanTable'].reloadData();
            },
            //列表查询
            queryData(queryData) {
                queryData["id"]=this.planId;
                queryProductUpdatePlanList(queryData).then(res => {
                    if (res.code === "0000") {
                        let {records, total} = res.data;
                        this.$refs.productPlanTable.updateTableData(records, total);
                    }
                });
            },
            //新增,打开弹窗
            add() {
                if (this.planId == null || this.planId == "") {
                    this.$Message.warning("请先保存修改信息！");
                    return;
                }else{
                    this.modalVisible = true;
                }
            },
            //关闭弹窗
            backInfo(){
                this.modalVisible = false;
            },
            //确定保存
            backResult(ids){
                this.prototypeForm.productPlan.ids = ids;
                this.submitLoading = true;
                saveProductUpdatePlan(this.prototypeForm.productPlan).then(res => {
                    this.submitLoading = false;
                    if (res.code === "0000") {
                        this.modalVisible = false;
                        this.refresh();
                    }
                }).catch(() => {
                    this.submitLoading = false;
                    this.modalVisible = false;
                });
            },
            //删除
            remove(row, index) {
                let self = this;
                self.$Modal.confirm({
                    title: "确认删除",
                    content: "您确认要删除?",
                    onOk: () => {
                        delUpdatePlanById(row.id).then(res => {
                            if (res.code === "0000") {
                                this.refresh();
                            }
                        })
                    }
                });
            },
            //子组件校验，传递到父组件
            validateForm() {
                let flag = true;
                this.prototypeForm.json = this.$refs.pricingParameters.formData;
                let parms = [
                    this.$refs.pricingParameters.getForm(),
                    this.$refs.prototypeForm,
                ];
                let flag1 = this.$refs['productSchemeSelection'].validateForm();
                let flag2 = this.$refs['repaymentMethodParameters'].validateForm();
                // 使用Promise.all去校验结果
                Promise.all(parms.map(this.getFormPromise)).then(res => {
                    const validateResult = res.every(item => !!item);
                    if (validateResult && flag1 && flag2) {
                        flag = true;
                    }
                });
                return flag;
            },
            //查看产品详情
            view(v) {
                // console.info("查看的数据："+JSON.stringify(v))
                this.afs.newTab(
                    this,'projects/afs-core-business/pages/product/product-plan/productProposalInformationShow',
                    '产品方案详情查看',
                    'ios-add',
                    {status: '3', productTemplateId: v.productTemplateId, id: v.productPlanId, templateCategory: v.templateCategory,productInheritanceType:null,op:'view'},
                    v.id,[],
                    true
                );
            },
        },
        computed: {
            defines() {
                return [
                    {
                        id: "productPlanDefine",
                        fields: productPlanDefine
                    }
                ];
            }
        },
    }
</script>
<style scoped>
    .common_br {
        background-color: #f7f7f7;
        border-radius: 3px;
        border: 1px solid #dcdee2;
    }
    .common_content {
        background-color: white;
        padding: 16px;
    }
    .basis-info>>>.ivu-input[disabled]{
        color: black;
    }
    .basis-info>>>.ivu-select-disabled .ivu-select-selected-value{
        color:#515a6e;
    }
    .basis-info>>>.ivu-input-number-input[disabled]{
        color:black;
    }
</style>
